package com.tiancikeji.zaoke.app.dao.code.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.tiancikeji.zaoke.app.dao.code.CodeDao;
import com.tiancikeji.zaoke.app.model.code.Code;

public class CodeDaoImpl extends JdbcDaoSupport implements CodeDao{

	private static final String TABLE = "`zaoke`.`code`";

	private static final String QUERY_VIEW = " `id`, `user_id`, `cell_phone`, `code`, `add_time` ";

	public long addCode(final Code code) {
		final String sql = "insert into " + TABLE + " (`user_id`, `cell_phone`, `code`, `add_time`) values(?, ?, ?, ?)";
		KeyHolder holder = new GeneratedKeyHolder();
		int count = getJdbcTemplate().update(new PreparedStatementCreator() {
			
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setObject(1, code.getUserId());
				ps.setObject(2, code.getCellPhone());
				ps.setObject(3, code.getCode());
				ps.setObject(4, code.getAddTime());
				return ps;
			}
		}, holder);
		
		if(count > 0 && holder.getKey() != null)
			return holder.getKey().longValue();
		
		return 0;
	}

	public Code getCodeInfo(long userid, long time) {
		String sql = "select " + QUERY_VIEW + " from " + TABLE + " where `user_id` = ? and `add_time` > ?";
		
		List<Code> codes = getJdbcTemplate().query(sql, new Object[]{userid, time}, new RowMapper<Code>() {

			public Code mapRow(ResultSet rs, int rowNum) throws SQLException {
				Code code = new Code();
				code.setId(rs.getLong("id"));
				code.setUserId(rs.getLong("user_id"));
				code.setCellPhone(rs.getString("cell_phone"));
				code.setCode(rs.getString("code"));
				code.setAddTime(rs.getLong("add_time"));
				return code;
			}
		});
		
		if(codes != null && codes.size() > 0)
			return codes.get(0);
		
		return null;
	}
}
